package com.lx.huimailf.fragment;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import com.lx.huimailf.utils.PullToRefreshView;
import com.lx.huimailf.utils.PullToRefreshView.OnFooterRefreshListener;
import com.lx.huimailf.utils.PullToRefreshView.OnHeaderRefreshListener;
import com.google.gson.Gson;
import com.lx.huimailf.R;
import com.lx.huimailf.activity.t_status_act.BackOrderDetialActivity;
import com.lx.huimailf.adapter.BackGoodsAdapter;
import com.lx.huimailf.adapter.OrderManagerAdapter;
import com.lx.huimailf.configs.Config;
import com.lx.huimailf.utils.DateTimePickDialogUtil;
import com.lx.huimailf.utils.PullToRefreshView;
import com.lx.huimailf.utils.TestDialog;
import com.lx.huimailf.weight.ActionItem;
import com.lx.huimailf.weight.TitlePopup;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import okhttp3.Call;

public class BackGoodsFragment extends Fragment implements OnHeaderRefreshListener, OnFooterRefreshListener {
    private PullToRefreshView mPullToRefreshView;
    private TitlePopup titlePopup;
    private TextView iv_show_Pop;
    private static RecyclerView recyclerView;
    private static String custid="";
    private static BackGoodsAdapter backGoodsAdapter;
    private AlertDialog dialog;
    private EditText etSearch;
    private ImageView search;
    private TextView tv1;
    private TextView tv2;
    private String linkerstatus;
    public static Fragment instance;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view= inflater.inflate(R.layout.fragment_back_goods, container, false);
        instance=this;
        inint(view);
        SharedPreferences sp=getActivity().getSharedPreferences("user", Context.MODE_PRIVATE);
        custid=sp.getString("custid","-1111");
        getBackGoodsInfo();
        mPullToRefreshView = (PullToRefreshView) view.findViewById(R.id.main_pull_refresh_view);
        mPullToRefreshView.setOnHeaderRefreshListener(this);
        mPullToRefreshView.setOnFooterRefreshListener(this);
        return view;
    }

    private void inint(final View view) {
        recyclerView=(RecyclerView)view.findViewById(R.id.recyclerview);
        iv_show_Pop=(TextView)view.findViewById(R.id.iv_show_Pop);

        etSearch=(EditText)view.findViewById(R.id.poi_et_search) ;
        search=(ImageView)view.findViewById(R.id.search) ;
        search.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(etSearch.length()==0){
                    Toast.makeText(getContext(),"请输入订单号",Toast.LENGTH_SHORT).show();
                }else {
                    Intent intent=new Intent();
                    intent.putExtra("orderno",etSearch.getText()+"");
                    intent.putExtra("status","12321343");
                    intent.setClass(getContext(), BackOrderDetialActivity.class);
                    startActivity(intent);
                }

            }
        });
        iv_show_Pop.setOnClickListener(new View.OnClickListener() {

            private String initStartDateTime = "2013年9月3日 14:44"; // 初始化开始时间
            private String initEndDateTime = "2014年8月23日 17:44"; // 初始化结束时间
            private Button ok;
            private  Button cancel;
            private List<String> list;
            private TextView myTextView;
            private Spinner mySpinner;
            private ArrayAdapter<String> adapter;
            @Override
            public void onClick(View v) {

                LayoutInflater inflater = getActivity().getLayoutInflater();
                View layout = inflater.inflate(R.layout.dialog_select1,(ViewGroup)view.findViewById(R.id.dialog_select));
                AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
                builder .setView(layout);
                dialog=builder.create();
                dialog.show();
                tv1=(TextView)layout.findViewById(R.id.tv1);
                tv2=(TextView) layout.findViewById(R.id.tv2);
                ok=(Button)layout.findViewById(R.id.ok);
                cancel=(Button)layout.findViewById(R.id.cancel);
                tv1.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        TestDialog dialog  = new TestDialog(getActivity(), R.style.Dialog);
                        dialog.setTitle("选择时间");
                        dialog.setBackButton("取消", new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                            }
                        });
                        dialog.setConfirmButton("确定", new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                tv1.setText(TestDialog.getDate());
                            }
                        });
                        dialog.show();


                    }
                });
                tv2.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        TestDialog dialog  = new TestDialog(getActivity(), R.style.Dialog);
                        dialog.setTitle("选择时间");
                        dialog.setBackButton("取消", new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                            }
                        });
                        dialog.setConfirmButton("确定", new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                tv2.setText(TestDialog.getDate());
                            }
                        });
                        dialog.show();

                    }
                });

                cancel.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        dialog.dismiss();
                    }
                });
                ok.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        selectOrder();
                    }
                });
                //添加一个下拉列表项的list，这里添加的项就是下拉列表的菜单项
                list = new ArrayList<String>();
                list.add("全部");
                list.add("拒绝");
                list.add("未审核");
                list.add("通过");
                mySpinner = (Spinner)layout.findViewById(R.id.Spinner_zhuangtai);
                //为下拉列表定义一个适配器，这里就用到里前面定义的list。
                adapter = new ArrayAdapter<String>(getContext(),android.R.layout.simple_spinner_item, list);
                //为适配器设置下拉列表下拉时的菜单样式。
                adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                //将适配器添加到下拉列表上
                mySpinner.setAdapter(adapter);
                //为下拉列表设置各种事件的响应，这个事响应菜单被选中
                mySpinner.setOnItemSelectedListener(new Spinner.OnItemSelectedListener(){
                    public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
                        // TODO Auto-generated method stub
                        if(arg2==0){
                            linkerstatus="";

                        }else if(arg2==1){
                            linkerstatus=String.valueOf(arg2-2);

                        }else if(arg2==2){
                            linkerstatus=String.valueOf(arg2-2);

                        } else if(arg2==3){
                        linkerstatus=String.valueOf(arg2-2);
                        }
                /* 将mySpinner 显示*/
                        arg0.setVisibility(View.VISIBLE);

                    }
                    public void onNothingSelected(AdapterView<?> arg0) {
                        // TODO Auto-generated method stub
                        myTextView.setText("NONE");
                        arg0.setVisibility(View.VISIBLE);
                    }
                });
        /*下拉菜单弹出的内容选项触屏事件处理*/
                mySpinner.setOnTouchListener(new Spinner.OnTouchListener(){
                    public boolean onTouch(View v, MotionEvent event) {
                        // TODO Auto-generated method stub
                        /**
                         *
                         */
                        return false;
                    }
                });
        /*下拉菜单弹出的内容选项焦点改变事件处理*/
                mySpinner.setOnFocusChangeListener(new Spinner.OnFocusChangeListener(){
                    public void onFocusChange(View v, boolean hasFocus) {
                        // TODO Auto-generated method stub

                    }
                });
            }

        });

    }

    /**
     * 获得退货信息
     */
    public static void getBackGoodsInfo(){
        HashMap<String,String> map=new HashMap<>();
        map.put("page","1");
        map.put("rows","200");
        map.put("linkerid",custid);
        Gson gson=new Gson();
        String parmas=gson.toJson(map);
        OkHttpUtils
                .post()
                .url(Config.url+"send/searchExiteOrder.do")
                .addParams("data",parmas)
                .addParams("mobile","true")
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {

                    }

                    @Override
                    public void onResponse(String response, int id) {
                        ArrayList<HashMap<String,String>> mList=new ArrayList<HashMap<String, String>>();
                        JSONArray jsonArray=null;
                        JSONObject jsonObject=null;
                        try {
                            jsonArray=new JSONArray(response);


                            for(int i=0;i<jsonArray.length();i++){
                                HashMap<String,String> map=new HashMap<String, String>();
                                map.put("orderno",jsonArray.getJSONObject(i).getString("orderno"));
                                map.put("createtime",jsonArray.getJSONObject(i).getString("createtime"));
                                map.put("sendstatus",jsonArray.getJSONObject(i).getString("sendstatus"));
                                map.put("exitecount",jsonArray.getJSONObject(i).getString("exitecount"));
                                map.put("exitemoney",jsonArray.getJSONObject(i).getString("exitmoney"));
                                map.put("custname",jsonArray.getJSONObject(i).getString("custname"));
                                map.put("exiteno",jsonArray.getJSONObject(i).getString("exiteno"));
                                map.put("exiteaddress",jsonArray.getJSONObject(i).getString("exiteaddress"));
                                map.put("linkerstatus",jsonArray.getJSONObject(i).getString("linkerstatus"));
                                map.put("id",jsonArray.getJSONObject(i).getString("id"));

                                map.put("name",jsonArray.getJSONObject(i).getString("name"));
                                map.put("array",String.valueOf(jsonArray.getJSONObject(i).getJSONArray("prolist")));
                                //      map.put("picname",Config.url+"tmp/"+jsonArray.getJSONObject(i).getString("picname"));
                                mList.add(map);

                            }
                            backGoodsAdapter=new BackGoodsAdapter(instance.getContext(),mList);
                            recyclerView.setLayoutManager(new LinearLayoutManager(instance.getContext()));
                            recyclerView.setAdapter(backGoodsAdapter);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }


                    }
                });
    }

    /**
     * 筛选
     */
    private void selectOrder(){
        HashMap<String,String> map=new HashMap<>();
        map.put("linkerid",custid);
        map.put("createtimeGE",tv1.getText().toString());
        map.put("createtimeLE",tv2.getText().toString());
        map.put("linkerstatus",linkerstatus);
        map.put("page","1");
        map.put("rows","20");
        Gson gson=new Gson();
        String parmas=gson.toJson(map);
        OkHttpUtils
                .post()
                .url(Config.url+"send/searchExiteOrder.do")
                .addParams("data",parmas)
                .addParams("mobile","true")
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        dialog.dismiss();
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        System.out.print("筛选成功=="+response);
                        dialog.dismiss();

                        ArrayList<HashMap<String,String>> mList=new ArrayList<HashMap<String, String>>();
                        JSONArray jsonArray=null;
                        JSONObject jsonObject=null;
                        try {
                            jsonObject=new JSONObject(response);
                            jsonArray=jsonObject.getJSONArray("list");
                            for(int i=0;i<jsonArray.length();i++){

                                HashMap<String,String> map=new HashMap<String, String>();
                                map.put("orderno",jsonArray.getJSONObject(i).getString("orderno"));
                                map.put("createtime",jsonArray.getJSONObject(i).getString("createtime"));
                                map.put("sendstatus",jsonArray.getJSONObject(i).getString("sendstatus"));
                                map.put("exitecount",jsonArray.getJSONObject(i).getString("exitecount"));
                                map.put("exitemoney",jsonArray.getJSONObject(i).getString("exitmoney"));
                                map.put("custname",jsonArray.getJSONObject(i).getString("custname"));
                                map.put("exiteno",jsonArray.getJSONObject(i).getString("exiteno"));
                                map.put("exiteaddress",jsonArray.getJSONObject(i).getString("exiteaddress"));
                                map.put("linkerstatus",jsonArray.getJSONObject(i).getString("linkerstatus"));
                                map.put("id",jsonArray.getJSONObject(i).getString("id"));
                            //    map.put("picname",Config.url+"tmp/"+jsonArray.getJSONObject(i).getString("picname"));
                                mList.add(map);

                            }
                            backGoodsAdapter=new BackGoodsAdapter(getContext(),mList);
                            recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
                            recyclerView.setAdapter(backGoodsAdapter);
                            backGoodsAdapter.notifyDataSetChanged();
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                });
    }
    @Override
    public void onFooterRefresh(PullToRefreshView view) {
        mPullToRefreshView.postDelayed(new Runnable() {

            @Override
            public void run() {
                handler.sendEmptyMessage(1);

                mPullToRefreshView.onFooterRefreshComplete();
            }
        }, 2000);
        getBackGoodsInfo();
    }

    @Override
    public void onHeaderRefresh(PullToRefreshView view) {
        mPullToRefreshView.postDelayed(new Runnable() {

            @Override
            public void run() {
                handler.sendEmptyMessage(1);
                mPullToRefreshView.onHeaderRefreshComplete();
            }
        }, 2000);
        getBackGoodsInfo();

    }
	/*-----------刷新接口方法实现-------	*/

    Handler handler = new Handler() {
        public void handleMessage(Message message) {
            super.handleMessage(message);
            mPullToRefreshView.onFooterRefreshComplete();

        }
    };
}